from django.shortcuts import render

# Create your views here.
from rest_framework.filters import OrderingFilter
from rest_framework.generics import GenericAPIView, ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

# GET /categories/(?P<category_id>\d+)/skus/
from goods.models import SKU
from goods.serializers import SKUSerializer, SKUIndexSerializer
from rest_framework.mixins import ListModelMixin
from drf_haystack.viewsets import HaystackViewSet


# GET /skus/search/？text=<搜索的关键字>   字符串传参
# 全文检索框架已经提供封装了一个HaystackViewSet，它会根据关键字检索索引记录
# 再由索引记录到数据库查询数据 不需要再写
class SKUSearchViewSet(HaystackViewSet):
    # 指定索引类对应的模型类  （根据关键字查询）
    index_models = [SKU]
    # 指定搜索结果返回时所采用的序列化器类
    # HayStack 搜索的每个结果对象包含两个属性
    # text 索引字段
    # object 搜索的模型对象（此处的模型对象就是商品的模型对象）
    serializer_class = SKUIndexSerializer

# class SKUListView(GenericAPIView):
#     serializer_class = SKUSerializer
#
#     def get(self, request, category_id):
#         """
#         self.kwargs:字典
#         获取分类SKU商品的数据
#         """
#         # 1、 根据category_id获取分类下ＳＫＵ数据
#         skus = SKU.objects.filter(category_id=category_id, is_launched=True)
#         # 2、将商品序列化返回
#         serializer = self.get_serializer(skus, many=True)
#         return Response(serializer.data)

# 升级1
# class SKUListView(ListModelMixin,GenericAPIView):
#     serializer_class = SKUSerializer
#     def get_queryset(self):
#         category_id = self.kwargs['category_id']
#         return SKU.objects.filter(category_id=category_id, is_launched=True)
#
#     def get(self, request, category_id):
#         """
#         self.kwargs:字典  保存从url中提取的参数
#         获取分类SKU商品的数据
#         """
#         return self.list(request)

# 升级2
class SKUListView(ListAPIView):
    serializer_class = SKUSerializer

    def get_queryset(self):
        category_id = self.kwargs['category_id']
        return SKU.objects.filter(category_id=category_id, is_launched=True)

    # 排序设置
    filter_backends = (OrderingFilter,)
    ordering_fields = ('update_time', 'price', 'sales')
